package com.htpay.service.impl;

import com.htpay.model.entity.Merchant;
import com.htpay.model.entity.MerchantLog;
import com.htpay.service.IBaseAPIService;
import com.htpay.util.IPUtils;
import com.htpay.util.ObjectConvertUtils;
import com.htpay.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

import com.htpay.mapper.*;

/**
 * @Description: 底层共通业务API，提供其他独立模块调用
 */
@Slf4j
@Service
public class BaseAPIServiceImpl implements IBaseAPIService {
    /**
     * 当前系统数据库类型
     */
    public static String DB_TYPE = "";

    @Resource
    private MerchantLogMapper merchantLogMapper;
    @Autowired
    private MerchantMapper userMapper;

    @Override
    public void addLog(String logContent, Integer logType, Integer operatetype) {
        MerchantLog sysLog = new MerchantLog();
        //注解上的描述,操作日志内容
        sysLog.setLogContent(logContent);
        sysLog.setLogType(logType);
        sysLog.setOperateType(operatetype);

        //请求的方法名
        //请求的参数

        try {
            //获取request
            HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
            //设置IP地址
            sysLog.setIp(IPUtils.getIpAddr(request));
        } catch (Exception e) {
            sysLog.setIp("127.0.0.1");
        }

        //获取登录用户信息
        Merchant sysUser = (Merchant) SecurityUtils.getSubject().getPrincipal();
        if (sysUser != null) {
            sysLog.setUserid(sysUser.getLoginName());
            sysLog.setUsername(sysUser.getRealName());

        }
        sysLog.setCreateTime(new Date());
        //保存系统日志
        merchantLogMapper.insert(sysLog);
    }

    @Override
    public Merchant getUserByName(String username) {
        if (ObjectConvertUtils.isEmpty(username)) {
            return null;
        }
        Merchant loginUser = new Merchant();
        Merchant merchant = userMapper.getUserByName(username);
        if (merchant == null) {
            return null;
        }
        BeanUtils.copyProperties(merchant, loginUser);
        return loginUser;
    }

    @Override
    public Merchant getUserById(String id) {
        if (ObjectConvertUtils.isEmpty(id)) {
            return null;
        }
        Merchant loginUser = new Merchant();
        Merchant merchant = userMapper.selectById(id);
        if (merchant == null) {
            return null;
        }
        BeanUtils.copyProperties(merchant, loginUser);
        return loginUser;
    }

}
